import React, { useRef, useState, useCallback, useContext, useEffect } from 'react'
import { connect } from 'react-redux'
import classnames from 'classnames'
import Context from '@/config/context'
import { getSearchResult } from 'api/base'
import { dealVideo, dealUser } from '@/redux/async'
import ScrollToTop from '@/components/ScrollToTop/ScrollToTop'
import { getPicUrl, formatDuration, formatCount } from 'utils/index'
const OrderType = [
    { name: '默认排序', value: 'totalrank' },
    { name: '播放多', value: 'click' },
    { name: '新发布', value: 'pubdate' },
    { name: '弹幕多', value: 'dm' }
]

const SearchType = [
    { name: '综合', value: 'video' },
    { name: 'UP主', value: 'bili_user' }
]
function Result(props) {
    const { keyword } = props
    const resultRef = useRef()
    const [page, setPage] = useState(1)
    const [loading, setLoading] = useState(false)
    const [videos, setVideos] = useState([])
    const [upUsers, setUpUsers] = useState([])
    const [tabkey, SetTabkey] = useState('video')
    const [itemkey, SetItemkey] = useState('totalrank')
    const govideo = useCallback((id) => {
        window.location.href = `/video/av/${id}`
    })
    const goUser = useCallback((id) => {
        window.location.href = `/space/${id}`
    })
    useEffect(() => {
        window.addEventListener('scroll', handleScroll, false)
        return () => {
            window.removeEventListener('scroll', handleScroll, false)
        }
    }, [])
    useEffect(() => {
        if (page <= 5) {
            setLoading(true)
            let data = {
                keyword,
                page,
                size: 10,
                searchType: tabkey,
                order: itemkey
            }
            getSearchResult(data).then((res) => {
                if (tabkey == 'video') {
                    let video = dealVideo(res.data.result)
                    setVideos((videos) => videos.concat(video))
                } else {
                    let user = dealUser(res.data.result)
                    setUpUsers((upUsers) => upUsers.concat(user))
                }
                setLoading(false)
            })
        }
    }, [keyword, tabkey, itemkey, page])

    const handleScroll = useCallback(() => {
        const resultDOM = resultRef.current
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        const height = window.innerHeight
        const contentHeight = resultDOM.offsetHeight
        if (scrollTop >= contentHeight - height) {
            setPage((page) => page + 1)
        }
    })

    return (
        <div className="reason" ref={resultRef}>
            <div className="tab flex">
                {SearchType.map((e) => (
                    <div
                        className="tab-item"
                        key={e.value}
                        onClick={() => {
                            SetTabkey(e.value)
                        }}
                    >
                        <span className={classnames('name', { current: tabkey == e.value })}>
                            {e.name}
                        </span>
                    </div>
                ))}
            </div>
            {tabkey == 'video' ? (
                <div className="av">
                    <div className="subtab flex around">
                        {OrderType.map((e) => (
                            <div
                                key={e.value}
                                onClick={() => {
                                    SetItemkey(e.value)
                                }}
                                className={classnames('sub-item', { current: itemkey == e.value })}
                            >
                                {e.name}
                            </div>
                        ))}
                    </div>
                    <div className="video-list">
                        {videos.map((e) => (
                            <div
                                onClick={() => {
                                    govideo(e.aId)
                                }}
                                className="flex middle video-item"
                                key={e.aid}
                            >
                                <div className="image-box mr10">
                                    <img
                                        src={getPicUrl('https:' + e.pic, '@200w_125h')}
                                        alt=""
                                        className="video-pic"
                                    />
                                    <div className="duration">{e.duration}</div>
                                </div>
                                <div className="cell-main">
                                    <p
                                        className="row2 mb5"
                                        dangerouslySetInnerHTML={{ __html: e.title }}
                                    />
                                    <div className="flex col-hui m middle mb5">
                                        <img
                                            src={require('../../assets/images/ico-up.png')}
                                            alt=""
                                            className="av-ico mr5"
                                        />
                                        <div className="owner">{e.owner.name}</div>
                                    </div>
                                    <div className="flex col-hui m middle">
                                        <div className="cell-main">
                                            <img
                                                src={require('../../assets/images/ico-play.png')}
                                                alt=""
                                                className="av-ico mr5"
                                            />
                                            {formatCount(e.playCount)}
                                        </div>
                                        <div className="cell-main">
                                            <img
                                                src={require('../../assets/images/ico-danmu.png')}
                                                alt=""
                                                className="av-ico mr5"
                                            />
                                            {formatCount(e.barrageCount)}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            ) : (
                <div className="up-list">
                    {upUsers.map((e, i) => (
                        <div
                            onClick={() => {
                                goUser(e.mId)
                            }}
                            key={i}
                            className="flex middle item"
                        >
                            <img
                                src={getPicUrl('https:' + e.face, '@120w_120h')}
                                alt=""
                                className="avatar"
                            />
                            <div className="cell-main ml10 overhide">
                                <div className="xl">{e.name}</div>
                                <div className="m col-hui">
                                    <span className="mr5">粉丝：{e.follower}</span>
                                    &nbsp;&nbsp;
                                    <span>视频：{e.videoCount}</span>
                                </div>
                                <div className=" m col-hui row1">{e.sign}</div>
                            </div>
                        </div>
                    ))}
                </div>
            )}
            {page >= 5 ? (
                <div className="tips">
                    <img src={require('../../assets/images/tips.png')} alt="" className="icon" />
                    <span className="text">刷到底了哟，从头再来吧 ~</span>
                </div>
            ) : loading ? (
                <div className="loading">(´・ω・｀)正在加载...</div>
            ) : null}
            <ScrollToTop />
        </div>
    )
}

export default connect(
    function mapStateToProps(state) {
        return state
    },
    function mapDispatchToProps(dispatch) {
        return { dispatch }
    }
)(Result)
